#include "http.h"
#include "WebSocketServer.h"
#include "check.h"
#include "threadpool.h"
#include <sstream>
#include <algorithm>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <cctype>
#include <iomanip>
#include <ctime>
#include <openssl/sha.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <netinet/in.h>
#include <fstream>
#include <fcntl.h>
using namespace std;

// ========== 包过滤全局变量 ==========
FirewallConfig firewall_config;
std::mutex firewall_mutex;
std::map<std::string, IPStats> ip_stats_map;

std::string current_time() {
    auto now = std::chrono::system_clock::now();
    auto in_time_t = std::chrono::system_clock::to_time_t(now);
    std::tm tm = *std::localtime(&in_time_t);
    
    std::stringstream ss;
    ss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
    return ss.str();
}
// 添加文件服务函数
void serve_file(int client_fd, const std::string& path, const std::string& content_type) {
    std::ifstream file(path, std::ios::binary);
    if (file) {
        std::string content((std::istreambuf_iterator<char>(file)), 
                     std::istreambuf_iterator<char>());
        
        std::string response = "HTTP/1.1 200 OK\r\n";
        response += "Content-Type: " + content_type + "\r\n";
        response += "Content-Length: " + std::to_string(content.size()) + "\r\n";
        response += "Connection: close\r\n\r\n";
        response += content;
        
        send(client_fd, response.c_str(), response.size(), 0);
    } else {
        const char* not_found = "HTTP/1.1 404 Not Found\r\n"
                               "Content-Type: text/plain\r\n"
                               "Connection: close\r\n\r\n"
                               "File not found";
        send(client_fd, not_found, strlen(not_found), 0);
    }
}
void http_print(const HttpRequest& request) {
    std::cout << "\n===== HTTP Request =====\n";
    
    // 打印请求行
    std::cout << "[" << static_cast<int>(request.get_parse_state()) << "] "
              << request.get_method_str() << " "
              << request.get_url();
    
    // 如果有查询字符串则打印
    if (!request.get_query().empty()) {
        std::cout << "?" << request.get_query();
    }
    
    std::cout << " " << request.get_http_version() << "\n";
    
    // 打印头部
    const auto& headers = request.get_headers();
    if (!headers.empty()) {
        std::cout << "--- Headers ---\n";
        for (const auto& [key, value] : headers) {
            std::cout << std::setw(20) << std::left << (key + ":") 
                      << value << "\n";
        }
    }
    
    // 打印查询参数
    const auto& query_params = request.get_query_params();
    if (!query_params.empty()) {
        std::cout << "--- Query Parameters ---\n";
        for (const auto& [key, value] : query_params) {
            std::cout << std::setw(20) << std::left << (key + ":") 
                      << value << "\n";
        }
    }
    
    // 打印消息体
    const auto& body = request.get_body();
    if (!body.empty()) {
        std::cout << "--- Body (" << body.size() << " bytes) ---\n";
        
        // 尝试检测是否是文本内容
        bool is_text = true;
        for (char c : body) {
            if (!std::isprint(static_cast<unsigned char>(c)) ){
                is_text = false;
                break;
            }
        }
        
        if (is_text) {
            std::cout << body << "\n";
        } else {
            std::cout << "<binary data>\n";
            // 打印十六进制预览
            const size_t preview_size = std::min<size_t>(body.size(), 16);
            for (size_t i = 0; i < preview_size; ++i) {
                printf("%02X ", static_cast<unsigned char>(body[i]));
            }
            if (body.size() > preview_size) std::cout << "...";
            std::cout << "\n";
        }
    }
    
    // 打印内容长度信息
    if (request.get_header("Content-Length").empty() && !body.empty()) {
        std::cout << "! Missing Content-Length header, actual body size: " 
                  << body.size() << " bytes\n";
    }
    
    std::cout << "=======================\n" << std::endl;
}
// 获取方法字符串表示
string HttpRequest::get_method_str() const {
    switch(method) {
        case Method::GET: return "GET";
        case Method::POST: return "POST";
        case Method::PUT: return "PUT";
        case Method::DELETE: return "DELETE";
        case Method::HEAD: return "HEAD";
        case Method::OPTIONS: return "OPTIONS";
        case Method::PATCH: return "PATCH";
        default: return "UNKNOWN";
    }
}
// 获取特定头部值
string HttpRequest::get_header(const string& name) const {
    // 转换为小写进行查找（HTTP头部不区分大小写）
    string lower_name = name;
    transform(lower_name.begin(), lower_name.end(), lower_name.begin(), 
        [](unsigned char c){ return tolower(c); });
    
    auto it = headers.find(lower_name);
    if (it != headers.end()) {
        return it->second;
    }
    return "";
}

// 获取特定查询参数
string HttpRequest::get_query_param(const string& name) const {
    auto it = query_params.find(name);
    if (it != query_params.end()) {
        return it->second;
    }
    return "";
}

// 重置解析器状态
void HttpRequest::reset() {
    method = Method::UNKNOWN;
    url.clear();
    http_version.clear();
    headers.clear();
    body.clear();
    query_params.clear();
    content_length = 0;
    state = ParseState::REQUEST_LINE;
    buffer.clear();
    body_bytes_received = 0;
    query_string.clear();
}

// 解析数据块
HttpRequest::ParseState HttpRequest::parse(const char* data, size_t length) {
    if (state == ParseState::COMPLETE || state == ParseState::ERROR) {
        return state;
    }

    // 将新数据添加到缓冲区
    buffer.append(data, length);

    // 根据当前状态进行解析
    while (state != ParseState::COMPLETE && state != ParseState::ERROR && !buffer.empty()) {
        switch (state) {
            case ParseState::REQUEST_LINE: {
                // 查找请求行结束标记
                size_t pos = buffer.find("\r\n");
                if (pos == string::npos) {
                    return state; // 等待更多数据
                }
                
                // 提取请求行
                string request_line = buffer.substr(0, pos);
                buffer.erase(0, pos + 2); // 移除已处理的数据
                
                if (!parse_request_line(request_line)) {
                    state = ParseState::ERROR;
                    return state;
                }
                
                state = ParseState::HEADERS;
                break;
            }
            
            case ParseState::HEADERS: {
                // 查找头部结束标记
                size_t pos = buffer.find("\r\n\r\n");
                if (pos == string::npos) {
                    // 检查是否至少有一个头部行结束
                    size_t line_end = buffer.find("\r\n");
                    if (line_end == string::npos) {
                        return state; // 等待更多数据
                    }
                    
                    // 尝试解析已存在的头部行
                    string headers_block = buffer.substr(0, line_end + 2);
                    parse_headers(headers_block);
                    buffer.erase(0, line_end + 2);
                } else {
                    // 提取整个头部块
                    string headers_block = buffer.substr(0, pos);
                    buffer.erase(0, pos + 4); // 移除头部块和空行
                    
                    parse_headers(headers_block);
                    
                    // 检查是否需要解析主体
                    content_length = 0;
                    string content_length_str = get_header("Content-Length");
                    if (!content_length_str.empty()) {
                        try {
                            content_length = stoul(content_length_str);
                        } catch (...) {
                            state = ParseState::ERROR;
                            return state;
                        }
                    }
                    
                    if (content_length > 0) {
                        state = ParseState::BODY;
                        body_bytes_received = 0;
                    } else {
                        state = ParseState::COMPLETE;
                    }
                }
                break;
            }
            
            case ParseState::BODY: {
                // 计算还需要多少字节
                size_t bytes_needed = content_length - body_bytes_received;
                size_t bytes_to_append = min(bytes_needed, buffer.size());
                
                // 添加数据到主体
                body.append(buffer.substr(0, bytes_to_append));
                buffer.erase(0, bytes_to_append);
                body_bytes_received += bytes_to_append;
                
                // 检查是否完成
                if (body_bytes_received >= content_length) {
                    state = ParseState::COMPLETE;
                }
                break;
            }
            
            default:
                state = ParseState::ERROR;
                break;
        }
    }
    
    return state;
}

// 解析请求行
// bool HttpRequest::parse_request_line(const string& line) {
//     istringstream iss(line);
//     string method_str;
    
//     if (!(iss >> method_str >> url >> http_version)) {
//         return false;
//     }
    
//     // 解析方法
//     method = parse_method(method_str);
//     if (method == Method::UNKNOWN) {
//         return false;
//     }
    
//     // 解析查询参数
//     parse_query_params();
    
//     return true;
// }
bool HttpRequest::parse_request_line(const string& line) {
    // 查找第一个空格（方法结束位置）
    size_t method_end = line.find(' ');
    if (method_end == string::npos || method_end == 0) {
        return false;
    }
    
    // 提取请求方法
    string method_str = line.substr(0, method_end);
    
    // 查找最后一个空格（HTTP版本开始位置）
    size_t version_start = line.rfind(' ');
    if (version_start == string::npos || version_start <= method_end + 1) {
        return false;
    }
    
    // 提取url（POST和HTTP版本之间的所有内容）
    // 注意：包含可能存在的空格和特殊字符
    url = line.substr(method_end + 1, version_start - method_end - 1);
    
    // 提取HTTP版本
    http_version = line.substr(version_start + 1);
    
    // 解析方法
    method = parse_method(method_str);
    if (method == Method::UNKNOWN) {
        return false;
    }
    
    return true; // 查询参数解析移到其他方法
}
// 解析方法
HttpRequest::Method HttpRequest::parse_method(const string& method_str) {
    if (method_str == "GET") return Method::GET;
    if (method_str == "POST") return Method::POST;
    if (method_str == "PUT") return Method::PUT;
    if (method_str == "DELETE") return Method::DELETE;
    if (method_str == "HEAD") return Method::HEAD;
    if (method_str == "OPTIONS") return Method::OPTIONS;
    if (method_str == "PATCH") return Method::PATCH;
    return Method::UNKNOWN;
}

// 解析头部
void HttpRequest::parse_headers(const string& headers_data) {
    istringstream iss(headers_data);
    string line;
    
    while (getline(iss, line)) {
        // 去除末尾的\r
        if (!line.empty() && line.back() == '\r') {
            line.pop_back();
        }
        
        // 跳过空行
        if (line.empty()) continue;
        
        size_t colon_pos = line.find(':');
        if (colon_pos != string::npos) {
            string name = line.substr(0, colon_pos);
            // 跳过冒号和空格
            size_t value_start = line.find_first_not_of(" \t", colon_pos + 1);
            if (value_start != string::npos) {
                string value = line.substr(value_start);
                // 头部名称转为小写以便不区分大小写查找
                transform(name.begin(), name.end(), name.begin(),
                    [](unsigned char c){ return tolower(c); });
                headers[name] = value;
            }
        }
    }
}

// 解析查询参数
void HttpRequest::parse_query_params() {
    // 提前截断url（可选但推荐）
    size_t query_start = url.find('?');
    if (query_start == string::npos) {
        return;
    }
    
    // 先更新url再去掉查询部分
    string original_url = url;
    url = original_url.substr(0, query_start);  // 提前截断
    
    // 获取查询字符串
    query_string = original_url.substr(query_start + 1);
    istringstream iss(query_string);  // 修复：使用query_string初始化
    
    string pair;
    while (getline(iss, pair, '&')) {
        size_t equal_pos = pair.find('=');
        if (equal_pos != string::npos) {
            string name = pair.substr(0, equal_pos);
            string value = pair.substr(equal_pos + 1);
            // 可选：添加URL解码函数 decode_url(name); decode_url(value);
            query_params[name] = value;
        } else if (!pair.empty()) {  // 处理无值参数（如"key"）
            query_params[pair] = "";
        }
        // 忽略空pair（如末尾的"&"）
    }
}

// 从客户端套接字接收并解析HTTP请求
HttpRequest receive_and_parse_request(int client_fd) {
    HttpRequest request;
    char buffer[4096];  // 4KB接收缓冲区
    
    while (true) {
        // 接收数据
        ssize_t bytes_received = recv(client_fd, buffer, sizeof(buffer), 0);
        
        if (bytes_received < 0) {
            // 处理接收错误
            cerr << "recv error: " << strerror(errno) << endl;
            break;
        } else if (bytes_received == 0) {
            // 客户端关闭连接
            cerr << "Client disconnected" << endl;
            break;
        }
        
        // 解析接收到的数据
        auto state = request.parse(buffer, bytes_received);
        
        if (state == HttpRequest::ParseState::COMPLETE) {
            // 请求解析完成
            return request;
        } else if (state == HttpRequest::ParseState::ERROR) {
            // 解析错误
            cerr << "HTTP request parsing error" << endl;
            request.reset();
            break;
        }
        
        // 如果请求未完成，继续接收数据
    }
    // 如果执行到这里，说明发生错误或连接关闭
    // 返回一个错误状态的HttpRequest对象
    request.reset();
    request.parse("", 0); // 强制进入错误状态
    return request;
}
std::atomic<bool> log_thread_running(false);
// void start_http_server(int port) {
//     // 创建 TCP 套接字
//     int server_fd = socket(AF_INET, SOCK_STREAM, 0);
//     if (server_fd < 0) {
//         std::cerr << "创建套接字失败" << std::endl;
//         return;
//     }
    
//     // 设置SO_REUSEADDR选项
//     int opt = 1;
//     if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
//         std::cerr << "设置SO_REUSEADDR失败" << std::endl;
//         close(server_fd);
//         return;
//     }
    
//     // 绑定到指定端口
//     sockaddr_in address{};
//     address.sin_family = AF_INET;
//     address.sin_addr.s_addr = INADDR_ANY;
//     address.sin_port = htons(port);
    
//     if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
//         std::cerr << "绑定端口 " << port << " 失败" << std::endl;
//         close(server_fd);
//         return;
//     }
    
//     // 开始监听
//     if (listen(server_fd, 10) < 0) {
//         std::cerr << "监听失败" << std::endl;
//         close(server_fd);
//         return;
//     }
    
//     std::cout << "HTTP服务器正在监听端口 " << port << "..." << std::endl;
    
//     while (true) {
//         // 接受客户端连接
//         sockaddr_in client_addr{};
//         socklen_t client_addrlen = sizeof(client_addr);
//         int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_addrlen);
//         cout<<"连接到新用户"<<endl;
//         if (client_fd < 0) {
//             std::cerr << "接受连接失败" << std::endl;
//             continue;
//         }
        
//         // 接收并解析 HTTP 请求
//         HttpRequest request = receive_and_parse_request(client_fd);
//         http_print(request);
        
//         if (request.get_parse_state() == HttpRequest::ParseState::COMPLETE) {
//             // std::string url = request.get_url();
//             //if (url == "/") {
//             //    serve_file(client_fd, "index.html", "text/html");
//             //} else if (url == "/styles.css") {
//             //    serve_file(client_fd, "styles.css", "text/css");
//             //} else if (url == "/script.js") {
//             //    serve_file(client_fd, "script.js", "application/javascript");
//             //} else {
//             string tem_ret=check(request);
//             LogMessage log_msg;
//             char client_ip[INET_ADDRSTRLEN];
//             inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
//             log_msg.client_ip = client_ip;
//             log_msg.method = request.get_method_str();
//             log_msg.url = request.get_url();
//             log_msg.result = (tem_ret == "1") ? "PASS" : "BLOCK: " + tem_ret;
//             log_msg.port = port;  // 当前监听端口
//             log_msg.timestamp = current_time();
//     // 添加到日志队列

//         std::lock_guard<std::mutex> lock(queue_mutex);
//         log_queue.push(log_msg);
//     queue_cv.notify_one();  
//         } else {
//             std::cerr << "请求解析失败" << std::endl;
//         }    
//         // 关闭客户端连接
//         close(client_fd);
//     }
//     // 关闭服务器套接字 (实际上不会执行到这里)
//     close(server_fd);
// }
void start_http_server(int port, int thread_count) {
    // 创建线程池
    ThreadPool pool(thread_count);
    
    // 创建 TCP 套接字
    int server_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (server_fd < 0) {
        cerr << "创建套接字失败: " << strerror(errno) << endl;
        return;
    }
    
    // 设置SO_REUSEADDR选项
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        cerr << "设置SO_REUSEADDR失败: " << strerror(errno) << endl;
        close(server_fd);
        return;
    }
    
    // 绑定到指定端口
    sockaddr_in address{};
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);
    
    if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
        cerr << "绑定端口 " << port << " 失败: " << strerror(errno) << endl;
        close(server_fd);
        return;
    }
    
    // 开始监听
    if (listen(server_fd, 1024) < 0) {
        cerr << "监听失败: " << strerror(errno) << endl;
        close(server_fd);
        return;
    }
    
    cout << "HTTP服务器正在监听端口 " << port << " (epoll+线程池)..." << endl;
    
    // 创建epoll实例
    int epoll_fd = epoll_create1(0);
    if (epoll_fd < 0) {
        cerr << "创建epoll失败: " << strerror(errno) << endl;
        close(server_fd);
        return;
    }
    
    // 添加服务器socket到epoll
    epoll_event server_event{};
    server_event.events = EPOLLIN | EPOLLET; // 边缘触发模式
    server_event.data.fd = server_fd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &server_event) < 0) {
        cerr << "添加服务器socket到epoll失败: " << strerror(errno) << endl;
        close(server_fd);
        close(epoll_fd);
        return;
    }
    
    // 事件缓冲区
    const int MAX_EVENTS = 64;
    epoll_event events[MAX_EVENTS];
    
    // 连接映射表
    map<int, Connection*> connections;
    
    while (true) {
        int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
        if (num_events < 0) {
            if (errno == EINTR) continue; // 被信号中断
            cerr << "epoll_wait失败: " << strerror(errno) << endl;
            break;
        }
        
        for (int i = 0; i < num_events; ++i) {
            int fd = events[i].data.fd;
            
            // 处理新连接
            if (fd == server_fd) {
                while (true) {
                    sockaddr_in client_addr{};
                    socklen_t client_addrlen = sizeof(client_addr);
                    int client_fd = accept4(server_fd, (struct sockaddr*)&client_addr, 
                                          &client_addrlen, SOCK_NONBLOCK);
                    
                    if (client_fd < 0) {
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
                            // 所有连接已处理
                            break;
                        }
                        cerr << "接受连接失败: " << strerror(errno) << endl;
                        continue;
                    }

                    // ========== 包过滤检查 ==========
                    if (should_block_connection(client_addr, port)) {
                        char ip_str[INET_ADDRSTRLEN];
                        inet_ntop(AF_INET, &(client_addr.sin_addr), ip_str, INET_ADDRSTRLEN);
                        
                        // 记录拦截日志
                        LogMessage log_msg;
                        log_msg.client_ip = ip_str;
                        log_msg.method = "TCP";
                        log_msg.url = "Packet Filter";
                        log_msg.result = "BLOCK: Firewall Blocked";
                        log_msg.port = port;
                        log_msg.timestamp = current_time();
                        
                        {
                            std::lock_guard<std::mutex> lock(queue_mutex);
                            log_queue.push(log_msg);
                            queue_cv.notify_one();
                        }
                        
                        close(client_fd);
                        continue;
                    }
                    
                    // 创建新连接
                    Connection* conn = new Connection();
                    conn->fd = client_fd;
                    conn->client_addr = client_addr;
                    connections[client_fd] = conn;
                    
                    // 添加到epoll
                    epoll_event client_event{};
                    client_event.events = EPOLLIN | EPOLLET | EPOLLRDHUP|EPOLLONESHOT;
                    client_event.data.fd = client_fd;
                    
                    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &client_event) < 0) {
                        cerr << "添加客户端到epoll失败: " << strerror(errno) << endl;
                        close(client_fd);
                        delete conn;
                        connections.erase(client_fd);
                    } else {
                        cout << "新连接: " << client_fd << " IP: " 
                             << inet_ntoa(client_addr.sin_addr) << endl;
                    }
                }
            } 
            // 连接关闭或错误
            else if (events[i].events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR)) {
                if (connections.find(fd) != connections.end()) {
                    close(fd);
                    delete connections[fd];
                    connections.erase(fd);
                    cout << "连接关闭: " << fd << endl;
                }
            }
            // 可读事件
            else if (events[i].events & EPOLLIN) {
                if (connections.find(fd) != connections.end()) {
                    Connection* conn = connections[fd];
                    
                    // ========== 慢速DoS检测 ==========
                    time_t now = time(nullptr);
                    if (conn->request.get_parse_state() == HttpRequest::ParseState::REQUEST_LINE ||
                        conn->request.get_parse_state() == HttpRequest::ParseState::HEADERS) {
                        
                        char ip_str[INET_ADDRSTRLEN];
                        inet_ntop(AF_INET, &(conn->client_addr.sin_addr), ip_str, INET_ADDRSTRLEN);
                        std::string client_ip(ip_str);
                        
                        std::lock_guard<std::mutex> lock(firewall_mutex);
                        IPStats& stats = ip_stats_map[client_ip];
                        
                        if (stats.connection_start == 0) {
                            stats.connection_start = now;
                        } else if ((now - stats.connection_start) > firewall_config.slow_dos_timeout) {
                            // 计算数据速率
                            double rate = static_cast<double>(stats.bytes_received) / 
                                         (now - stats.connection_start);
                            
                            if (rate < firewall_config.slow_dos_min_rate) {
                                // 检测到慢速DoS攻击
                                stats.banned_until = now + firewall_config.syn_flood_ban_time;
                                
                                // 关闭连接
                                close(fd);
                                delete conn;
                                connections.erase(fd);
                                
                                // 记录日志
                                LogMessage log_msg;
                                log_msg.client_ip = client_ip;
                                log_msg.method = "TCP";
                                log_msg.url = "Slow DoS Attack";
                                log_msg.result = "BLOCK: Slow DoS Detected";
                                log_msg.port = port;
                                log_msg.timestamp = current_time();
                                
                                {
                                    std::lock_guard<std::mutex> lock(queue_mutex);
                                    log_queue.push(log_msg);
                                    queue_cv.notify_one();
                                }
                                
                                continue;
                            }
                        }
                    }

                    // 读取数据
                    char buffer[4096];
                    ssize_t bytes_read;
                    while ((bytes_read = recv(fd, buffer, sizeof(buffer), 0)) > 0) {
                        conn->recv_buffer.append(buffer, bytes_read);
                        
                        // 解析HTTP请求
                        auto state = conn->request.parse(conn->recv_buffer.c_str(), conn->recv_buffer.size());
                        
                        if (state == HttpRequest::ParseState::COMPLETE) {
                            // 提交任务到线程池
                              connections.erase(fd);
                            pool.enqueue([conn,port] {
                                // 处理请求
                                http_print(conn->request);
                                
                                string tem_ret = check(conn->request);
                                LogMessage log_msg;
                                char client_ip[INET_ADDRSTRLEN];
                                inet_ntop(AF_INET, &conn->client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
                                log_msg.client_ip = client_ip;
                                log_msg.method = conn->request.get_method_str();
                                log_msg.url = conn->request.get_url();
                                log_msg.result = (tem_ret == "1") ? "PASS" : "BLOCK: " + tem_ret;
                                log_msg.port = port;
                                log_msg.timestamp = current_time();
                                
                                // 添加到日志队列
                                {
                                    std::lock_guard<std::mutex> lock(queue_mutex);
                                    log_queue.push(log_msg);
                                    queue_cv.notify_one();
                                }
                                
                                // 构造响应
                                string response = "HTTP/1.1 200 OK\r\n";
                                response += "Content-Type: text/plain\r\n";
                                response += "Connection: close\r\n\r\n";
                                response += tem_ret;
                                
                                // 发送响应
                                send(conn->fd, response.c_str(), response.size(), 0);
                                
                                // 关闭连接
                                close(conn->fd);
                            });
                            
                            // 移除连接
                          //  epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, nullptr);
                          //  connections.erase(fd);
                          //  break;
                        } 
                        else if (state == HttpRequest::ParseState::ERROR) {
                            cerr << "请求解析错误: " << fd << endl;
                            close(fd);
                            delete conn;
                            connections.erase(fd);
                            break;
                        }
                    }
                    
                    // 处理读取错误
                    if (bytes_read < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
                        cerr << "读取错误: " << strerror(errno) << " on fd: " << fd << endl;
                        close(fd);
                        delete conn;
                        connections.erase(fd);
                    }
                }
            }
        }
    }
    
    // 清理资源
    for (auto& pair : connections) {
        close(pair.first);
        delete pair.second;
    }
    close(server_fd);
    close(epoll_fd);
}

bool should_block_connection(const sockaddr_in& client_addr, int port) {
    char ip_str[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(client_addr.sin_addr), ip_str, INET_ADDRSTRLEN);
    std::string client_ip(ip_str);
    
    time_t now = time(nullptr);
    
    std::lock_guard<std::mutex> lock(firewall_mutex);
    
    // 检查是否在封禁列表中
    auto it = ip_stats_map.find(client_ip);
    if (it != ip_stats_map.end() && it->second.banned_until > now) {
        return true;
    }
    
    // 检查端口过滤
    if (firewall_config.blocked_ports.find(port) != firewall_config.blocked_ports.end()) {
        return true;
    }
    
    // 更新IP统计信息
    IPStats& stats = ip_stats_map[client_ip];
    
    // SYN洪水检测
    if (stats.last_syn_time > 0 && (now - stats.last_syn_time) <= 1) {
        stats.syn_count++;
        
        if (stats.syn_count > firewall_config.syn_flood_threshold) {
            stats.banned_until = now + firewall_config.syn_flood_ban_time;
            return true;
        }
    } else {
        stats.syn_count = 1;
        stats.last_syn_time = now;
    }
    
    return false;
}